import asyncio

from loguru import logger

from com.arcfox.base.base_spider import ExecuteType
from com.arcfox.manager.redis_task_manager import RedisTaskManager
from com.arcfox.school.parse.enroll_ment_plain_parse import EnrollMentPlainParse
from com.arcfox.school.parse.jzy_major_parse import MajorParser

from com.arcfox.school.parse.yifen_yiduan_parse import YifenYiduanParser
from com.arcfox.school.processor.jzy.jzy_enroll_ment_plain_processor import EnrollMentPlainProcessor
from com.arcfox.school.spider.jzy.jzy_base_spider import JZYBaseSpider
from com.arcfox.util import async_request as requests, util
from com.arcfox.util.util import random_sleep
from com.arcfox.middleware.proxy_zhima_middleware import get_proxy, format_proxy

'''
    一分一段
'''


class EnrollmentPlanSpider(JZYBaseSpider):
    def __init__(self):
        super().__init__()
        self.parser = EnrollMentPlainParse()
        self.processor = EnrollMentPlainProcessor()
        self.task_manager = RedisTaskManager(self.TASK_SCHOOL_ZSJH_LIST_JZY)

    async def _pull_task(self):
        return await self.task_manager.pull_tasks(10), ExecuteType.FINISH

    async def _crawl_by_task(self, tasks):
        await self.init_session()
        formatted_proxy = None
        for task in tasks:
            result_url_list = self.parser.parse_plain_url_list(self.get_province_map(), task["id"])
            for parse_result in result_url_list:
                try:
                    for i in range(3):
                        logger.info("请求url:{},几次：{}", parse_result["url"], i)
                        resp = await requests.get(self.session, url=parse_result["url"],
                                                  headers=self.get_default_header(),
                                                  proxy=formatted_proxy)
                        if resp.code == 200:
                            result_list = self.parser.parse_plain_result_list(resp.json(),
                                                                              self.get_province_map_reverse(),
                                                                              task["school_name"])
                            # 获取数量
                            await self.processor.store_enroll_plan(tasks=result_list)
                            break
                        else:
                            proxy = await get_proxy()
                            await random_sleep(10)
                            formatted_proxy = format_proxy(proxy)
                            logger.info("命中风控, 更换 IP")
                    # await random_sleep(0.5)
                except asyncio.exceptions.TimeoutError as e:
                    proxy = await get_proxy()
                    formatted_proxy = format_proxy(proxy)
                    logger.error("命中风控, 休眠10分钟", e)
                    await random_sleep(10 * 60)
                    await self.task_manager.add_fail_tasks(task)


if __name__ == "__main__":
    asyncio.run(EnrollmentPlanSpider().start_crawl())
